﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace GordonKristan.codeclean
{
	class CommentEditModule
	{
		private String document;
		private ArrayList chunks;

		/// <summary>
		/// Default constructor.
		/// </summary>
		/// <param name="aDoc">Document to parse and edit</param>
		public CommentEditModule(String aDoc)
		{
			document = aDoc;
			chunks = new ArrayList();
			parseDocumnet();
		}

		/// <summary>
		/// Parses the document into comments.
		/// </summary>
		private void parseDocumnet()
		{
			CommentLexer lex = new CommentLexer(document);
			ArrayList pairs = lex.getComments();
			StringContainer current;
			//Create the first chunk if it's not a comment
			if (((TextPair)pairs[0]).start != 0)
			{
				current = new StringContainer();
				current.comment = false;
				current.start = 0;
				current.length = ((TextPair)pairs[0]).start;
				current.oldText = document.Substring(0, current.length);
				current.newText = current.oldText;
				chunks.Add(current);
			}
			//Add all but the last one
			for (int i = 0; i < pairs.Count; ++i)
			{
				current = new StringContainer();
				current.comment = true;
				current.start = ((TextPair)pairs[i]).start;
				current.length = ((TextPair)pairs[i]).end - ((TextPair)pairs[i]).start + 1;
				current.oldText = document.Substring(current.start, current.length);
				current.newText = current.oldText;
				chunks.Add(current);
				//If there's space in between this comment and the next, add it
				if (i < pairs.Count - 1 && ((TextPair)pairs[i + 1]).start - ((TextPair)pairs[i]).end != 0)
				{
					current = new StringContainer();
					current.comment = false;
					current.start = ((TextPair)pairs[i]).end + 1;
					current.length = ((TextPair)pairs[i + 1]).start - current.start;
					current.oldText = document.Substring(current.start, current.length);
					current.newText = current.oldText;
					chunks.Add(current);
				}
			}
			//See if there's extra space at the end
			if (((TextPair)pairs[pairs.Count - 1]).end < document.Length - 1)
			{
				current = new StringContainer();
				current.comment = false;
				current.start = ((TextPair)pairs[pairs.Count - 1]).end + 1;
				current.length = document.Length - current.start;
				current.oldText = document.Substring(current.start, current.length);
				current.newText = current.oldText;
				chunks.Add(current);
			}
		}

		/// <summary>
		/// Retrieves all of the parsed comments from the document.
		/// </summary>
		/// <returns>ArrayList of CommentContainers</returns>
		public ArrayList getComments()
		{
			return chunks;
		}
	}
}
